// main.go
package main

import (
	"flag"
	"fmt"
	"os"
	"path/filepath"
	"strconv"

	pb "goHupuWalker/gproto"

	log "github.com/alecthomas/log4go"
	"golang.org/x/net/context"
	"google.golang.org/grpc"
)

func usage(ret int) {
	fmt.Fprintf(os.Stderr, `Usage: %s [flags] cmd param ...`, filepath.Base(os.Args[0]))
	fmt.Fprintln(os.Stderr, "")
	fmt.Fprintln(os.Stderr, `Flags:`)
	fmt.Fprintln(os.Stderr, `  --help  show this help`)
	fmt.Fprintln(os.Stderr, `  --svr   server address, default: 127.0.0.1`)
	fmt.Fprintln(os.Stderr, `  --port  server port, default: 50001`)
	fmt.Fprintln(os.Stderr, `Cmds:`)
	fmt.Fprintln(os.Stderr, ` duration <min>: Set walker duration as N(5-60) mins`)
	fmt.Fprintln(os.Stderr, ` start: Start walker right now`)
	fmt.Fprintln(os.Stderr, "")
	os.Exit(ret)
}

func chk_duration(params []string) bool {
	if len(params) != 1 {
		return false
	}

	d, err := strconv.Atoi(params[0])
	if err != nil || d < 5 || d > 60 {
		return false
	}

	return true
}

func chk_start(params []string) bool {
	return len(params) == 0
}

func cmd_duration(cli *pb.HupuWalkerClient, params []string) (int, string) {
	d, _ := strconv.Atoi(params[0])
	r, err := (*cli).SetDuration(context.Background(), &pb.SetDurationRequest{DurationInMin: int32(d)})
	if err != nil {
		return 3, fmt.Sprintf("%v", err)
	}

	return int(r.ErrorCode), r.ErrorMsg
}

func cmd_start(cli *pb.HupuWalkerClient, params []string) (int, string) {
	r, err := (*cli).Start(context.Background(), &pb.StartRequest{})
	if err != nil {
		return 3, fmt.Sprintf("%v", err)
	}

	return int(r.ErrorCode), r.ErrorMsg
}

func main() {
	flag.Usage = func() {
		usage(1)
	}

	helpPtr := flag.Bool("help", false, "show this help")
	serverPtr := flag.String("svr", "127.0.0.1", "server address")
	portPtr := flag.Int("port", 50001, "server port")

	flag.Parse()
	args := flag.Args()

	if *helpPtr {
		usage(0)
	}

	if len(args) < 1 {
		usage(1)
	}

	cmdCheckMap := map[string]func([]string) bool{
		"duration": chk_duration,
		"start":    chk_start}

	cmdExecMap := map[string]func(*pb.HupuWalkerClient, []string) (int, string){
		"duration": cmd_duration,
		"start":    cmd_start}

	cmdFunc, exists := cmdExecMap[args[0]]
	if !exists {
		usage(1)
	}

	cmdCheck, _ := cmdCheckMap[args[0]]
	if cmdCheck != nil && !cmdCheck(args[1:]) {
		usage(2)
	}

	addr := fmt.Sprintf("%s:%d", *serverPtr, *portPtr)
	conn, err := grpc.Dial(addr, grpc.WithInsecure())
	if err != nil {
		log.Error("Error: Connection failed, %v", err)
	}
	defer conn.Close()

	cli := pb.NewHupuWalkerClient(conn)

	code, msg := cmdFunc(&cli, args[1:])
	if code != 0 {
		fmt.Fprintf(os.Stderr, `Error %d: %s`, code, msg)
		fmt.Fprintln(os.Stderr, "")
		os.Exit(code)
	} else {
		fmt.Println("done")
	}
}
